package com.xuyuan.concurrent.lock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreExampleDemo {
    private static Semaphore semaphore = null;

    public SemaphoreExampleDemo() {
        semaphore = new Semaphore(3); // 设置许可数量为3
    }

    public static void main(String[] args) {
        SemaphoreExampleDemo resourcePool = new SemaphoreExampleDemo();

        ExecutorService executorService= Executors.newFixedThreadPool(10);
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            executorService.submit(()-> {
                try {
                    Integer workerId= finalI;
                    boolean result = semaphore.tryAcquire(5000, TimeUnit.MILLISECONDS);// 获取许可
                    if(result) System.out.println("工人"+workerId+"获取许可成功");
                    else System.out.println("工人"+workerId+"获取许可失败");
                    Thread.sleep(3000);
                    semaphore.release();
                } catch (InterruptedException e) {}
            });
        }
        executorService.shutdown();
        if(executorService.isTerminated()) System.out.println("任务完成。。。。。。。。。。");
    }
}